package com.example.order.fragment;

import android.content.Context;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.Fragment;

import com.example.order.R;
import com.example.order.pojo.Window;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class AdminManageWindowFragment extends Fragment {

    TextView titleTextView;
    ListView userListView;
    Button addWindowButton, editButton, deleteButton, refreshButton;

    private static final String BASE_URL = "http://10.2.0.232:8080/backend-api-endpoint";


    public AdminManageWindowFragment() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_manage_window, container, false);

        // Get references to UI elements
        titleTextView = view.findViewById(R.id.titleTextView);
        userListView = view.findViewById(R.id.userListView);
        addWindowButton = view.findViewById(R.id.addWindowButton);
        editButton = view.findViewById(R.id.editButton);
        deleteButton = view.findViewById(R.id.deleteButton);
        refreshButton = view.findViewById(R.id.refreshButton);

        // Set ListView choice mode
        userListView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);

        addWindowButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showAddWindowDialog();
            }
        });

        editButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int selectedPosition = userListView.getCheckedItemPosition();
                if (selectedPosition != ListView.INVALID_POSITION) {
                    Window selectedWindow = (Window) userListView.getItemAtPosition(selectedPosition);
                    showEditWindowDialog(selectedWindow);
                } else {
                    Toast.makeText(getActivity(), "请先选择要编辑的窗口", Toast.LENGTH_SHORT).show();
                }
            }
        });

        refreshButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getAllWindows();
            }
        });

        deleteButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int selectedPosition = userListView.getCheckedItemPosition();
                if (selectedPosition != ListView.INVALID_POSITION) {
                    Window selectedWindow = (Window) userListView.getItemAtPosition(selectedPosition);
                    showDeleteConfirmationDialog(selectedWindow);
                } else {
                    Toast.makeText(getActivity(), "请先选择要删除的窗口", Toast.LENGTH_SHORT).show();
                }
            }
        });

        // Call the method to get all windows when the fragment is created
        getAllWindows();

        return view;
    }

    private class AddWindowTask extends AsyncTask<Window, Void, String> {
        @Override
        protected String doInBackground(Window... windows) {
            OkHttpClient client = new OkHttpClient();
            String url = BASE_URL + "/addWindow";

            // 构建 JSON 请求体
            MediaType JSON = MediaType.parse("application/json; charset=utf-8");
            JSONObject json = new JSONObject();
            try {
                json.put("window_id", windows[0].getWindow_id());
                json.put("window_password", windows[0].getWindow_password());
                json.put("window_name", windows[0].getWindow_name());
                json.put("contact", windows[0].getContact());
            } catch (JSONException e) {
                e.printStackTrace();
            }

            RequestBody requestBody = RequestBody.create(JSON, json.toString());

            // 构建 HTTP 请求
            Request request = new Request.Builder()
                    .url(url)
                    .post(requestBody)
                    .build();

            try {
                // 执行请求
                Response response = client.newCall(request).execute();

                // 处理响应
                if (response.isSuccessful()) {
                    return response.body().string();
                } else {
                    return "Error: " + response.code();
                }
            } catch (IOException e) {
                e.printStackTrace();
                return "Error: " + e.getMessage();
            }
        }

        @Override
        protected void onPostExecute(String result) {
            // 处理结果，例如向窗口显示消息
            Toast.makeText(getActivity(), result, Toast.LENGTH_SHORT).show();
            // 你还可以通过再次调用 getAllWindows() 来刷新 userListView
            getAllWindows();
        }
    }

    private class GetAllWindowsTask extends AsyncTask<Void, Void, List<Window>> {
        @Override
        protected List<Window> doInBackground(Void... voids) {
            OkHttpClient client = new OkHttpClient();
            String url = BASE_URL + "/getAllWindows";

            Request request = new Request.Builder()
                    .url(url)
                    .get()
                    .build();

            try {
                Response response = client.newCall(request).execute();

                if (response.isSuccessful()) {
                    String responseBody = response.body().string();
                    // 解析获取到的窗口列表
                    List<Window> windowList = parseWindowList(responseBody);
                    return windowList;
                } else {
                    Log.e("GetAllWindows", "Error: " + response.code());
                    return null;
                }
            } catch (IOException e) {
                e.printStackTrace();
                Log.e("GetAllWindows", "Error: " + e.getMessage());
                return null;
            }
        }

        public class WindowAdapter extends ArrayAdapter<Window> {
            public WindowAdapter(Context context, List<Window> windows) {
                super(context, R.layout.admin_list_item_layout, windows);
            }

            @NonNull
            @Override
            public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
                if (convertView == null) {
                    convertView = LayoutInflater.from(getContext()).inflate(R.layout.admin_list_item_layout, parent, false);
                }

                Window window = getItem(position);

                TextView text1 = convertView.findViewById(R.id.text1);
                TextView text2 = convertView.findViewById(R.id.text2);
                TextView text3 = convertView.findViewById(R.id.text3);

                text1.setText("窗口ID: " + window.getWindow_id());
                text2.setText("窗口名: " + window.getWindow_name());
                text3.setText("密码: " + window.getWindow_password());

                return convertView;
            }
        }

        @Override
        protected void onPostExecute(List<Window> windowList) {
            if (windowList != null) {
                // 创建适配器
                AdminManageWindowFragment.GetAllWindowsTask.WindowAdapter adapter = new GetAllWindowsTask().new WindowAdapter(getActivity(), windowList);

                // 将适配器设置到ListView
                userListView.setAdapter(adapter);

                for (Window window : windowList) {
                    Log.d("WindowInfo", "ID: " + window.getWindow_id() + ", Name: " + window.getWindow_name());
                    // 根据需要在界面上显示窗口信息
                }
            }
        }
    }

    private List<Window> parseWindowList(String responseBody) {
// 实现解析JSON的逻辑，将数据转换成 Window 对象列表
        // 这里需要根据您后端返回的数据格式进行解析
        // 示例代码，具体根据实际情况修改
        List<Window> windowList = new ArrayList<>();
        try {
            JSONArray jsonArray = new JSONArray(responseBody);
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject jsonWindow = jsonArray.getJSONObject(i);
                Window window = new Window();
                window.setWindow_id(jsonWindow.getString("window_id"));
                window.setWindow_name(jsonWindow.getString("window_name"));
                window.setWindow_password(jsonWindow.getString("window_password"));
                // 其他字段的解析
                windowList.add(window);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return windowList;    }

    public void getAllWindows() {
        new GetAllWindowsTask().execute();
    }

    private void showAddWindowDialog() {
// 使用 AlertDialog.Builder 创建对话框
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setTitle("Add New Window");

        // 使用 LayoutInflater 加载自定义布局
        LayoutInflater inflater = getLayoutInflater();
        View dialogView = inflater.inflate(R.layout.dialog_add_window, null);
        builder.setView(dialogView);

        // 获取对话框中的 EditText
        final EditText etUserId = dialogView.findViewById(R.id.etWindowId);
        final EditText etUserName = dialogView.findViewById(R.id.etWindowName);
        final EditText etUserPassword = dialogView.findViewById(R.id.etWindowPassword);
        final EditText etContact = dialogView.findViewById(R.id.etContact);
        final EditText etReservationResult = dialogView.findViewById(R.id.etReservationResult);

        // 设置对话框按钮
        builder.setPositiveButton("Add", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // 获取窗口输入的信息
                String userId = etUserId.getText().toString();
                String userName = etUserName.getText().toString();
                String userPassword = etUserPassword.getText().toString();
                String contact = etContact.getText().toString();
                String reservationResult = etReservationResult.getText().toString();

                // 判断必填字段是否为空
                if (userId.isEmpty() || userPassword.isEmpty()) {
                    // 提示窗口必填字段不能为空
                    Toast.makeText(getActivity(), "Window ID and Password are required fields", Toast.LENGTH_SHORT).show();
                } else {
                    // 创建新的 Window 对象
                    Window newWindow = new Window(userId, userName, userPassword, contact, reservationResult);

                    // 调用添加窗口的方法
                    addWindow(newWindow);
                }
            }
        });

        builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // 窗口点击取消，不执行任何操作
            }
        });

        // 显示对话框
        builder.create().show();    }

    private void showEditWindowDialog(final Window selectedWindow) {
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setTitle("编辑窗口");

        LayoutInflater inflater = getLayoutInflater();
        View dialogView = inflater.inflate(R.layout.dialog_add_user, null);
        builder.setView(dialogView);

        // 获取对话框中的 EditText
        final EditText etUserId = dialogView.findViewById(R.id.etUserId);
        final EditText etUserName = dialogView.findViewById(R.id.etUserName);
        final EditText etUserPassword = dialogView.findViewById(R.id.etUserPassword);
        final EditText etContact = dialogView.findViewById(R.id.etContact);
        final EditText etReservationResult = dialogView.findViewById(R.id.etReservationResult);

        // 预填充数据
        etUserId.setText(selectedWindow.getWindow_id());
        etUserName.setText(selectedWindow.getWindow_name());
        etUserPassword.setText(selectedWindow.getWindow_password());
        etContact.setText(selectedWindow.getContact());

        builder.setPositiveButton("保存", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // 获取编辑后的窗口信息
                String userId = etUserId.getText().toString();
                String userName = etUserName.getText().toString();
                String userPassword = etUserPassword.getText().toString();
                String contact = etContact.getText().toString();
                String reservationResult = etReservationResult.getText().toString();

                // 更新窗口
                Window editedWindow = new Window(userId, userName, userPassword, contact, reservationResult);
                editWindow(selectedWindow.getWindow_id(), editedWindow);
            }
        });

        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // 窗口取消编辑
            }
        });

        builder.create().show();    }

    public void addWindow(Window newWindow) {
        new AddWindowTask().execute(newWindow);
    }

    public void editWindow(String windowId, Window editedWindow) {
        new EditWindowTask().execute(windowId, editedWindow);
    }

    private class EditWindowTask extends AsyncTask<Object, Void, String> {
        @Override
        protected String doInBackground(Object... params) {
            // 获取参数
            String windowId = (String) params[0];
            Window editedWindow = (Window) params[1];

            OkHttpClient client = new OkHttpClient();
            String url = BASE_URL + "/editWindow";

            // 构建 JSON 请求体
            MediaType JSON = MediaType.parse("application/json; charset=utf-8");
            JSONObject json = new JSONObject();
            try {
                json.put("window_id", editedWindow.getWindow_id());
                json.put("window_password", editedWindow.getWindow_password());
                json.put("window_name", editedWindow.getWindow_name());
                json.put("contact", editedWindow.getContact());
            } catch (JSONException e) {
                e.printStackTrace();
            }

            RequestBody requestBody = RequestBody.create(JSON, json.toString());

            // 构建 HTTP 请求
            Request request = new Request.Builder()
//                    .url(url + "/" + windowId)  // 注意：这里可能需要在URL中包含要更新的窗口ID
                    .url(url)
                    .post(requestBody)
                    .build();

            try {
                // 执行请求
                Response response = client.newCall(request).execute();

                // 处理响应
                if (response.isSuccessful()) {
                    return response.body().string();
                } else {
                    return "Error: " + response.code();
                }
            } catch (IOException e) {
                e.printStackTrace();
                return "Error: " + e.getMessage();
            }
        }

        @Override
        protected void onPostExecute(String result) {
            // 处理结果，例如向窗口显示消息
            Log.d("AsyncTaskResult", "Result: " + result);
            Toast.makeText(getActivity(), result, Toast.LENGTH_SHORT).show();
            // 你还可以通过再次调用 getAllWindows() 来刷新 userListView
            getAllWindows();
        }    }

    private void showDeleteConfirmationDialog(final Window windowToDelete) {
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setTitle("确认删除");
        builder.setMessage("确定要删除窗口 " + windowToDelete.getWindow_id() + " 吗？");

        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // 窗口确认删除，调用删除窗口的方法
                deleteWindow(windowToDelete.getWindow_id());
            }
        });

        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // 窗口取消删除
            }
        });

        builder.create().show();    }

    public void deleteWindow(String windowId) {
        new DeleteWindowTask().execute(windowId);
    }

    private class DeleteWindowTask extends AsyncTask<String, Void, String> {
        @Override
        protected String doInBackground(String... params) {
            String windowId = params[0];
            OkHttpClient client = new OkHttpClient();
            String url = BASE_URL + "/deleteWindow";

            // 构建 JSON 请求体
            MediaType JSON = MediaType.parse("application/json; charset=utf-8");
            JSONObject json = new JSONObject();
            try {
                json.put("window_id", windowId);
            } catch (JSONException e) {
                e.printStackTrace();
            }

            RequestBody requestBody = RequestBody.create(JSON, json.toString());

            // 构建 HTTP 请求
            Request request = new Request.Builder()
//                    .url(url + "/" + windowId)
                    .url(url)
                    .post(requestBody)  // 使用 POST 请求，因为后端接口要求请求体
                    .build();

            try {
                // 执行请求
                Response response = client.newCall(request).execute();

                // 处理响应
                if (response.isSuccessful()) {
                    return response.body().string();
                } else {
                    return "Error: " + response.code();
                }
            } catch (IOException e) {
                e.printStackTrace();
                return "Error: " + e.getMessage();
            }
        }

        @Override
        protected void onPostExecute(String result) {
            // 处理结果，例如向窗口显示消息
            Log.d("AsyncTaskResult", "Result: " + result);
            Toast.makeText(getActivity(), result, Toast.LENGTH_SHORT).show();
            // 刷新窗口列表
            getAllWindows();
        }
    }
}
